package com.xiang.community.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiang.community.entity.User;
import com.xiang.community.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import static com.xiang.community.constant.RedisUtilConstant.PREFIX_USER;

/**
 * @author qixiangLi
 * @Date 2021/12/5
 */
@Service
@Slf4j
public class CommonService {
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private ObjectMapper mapper;
    @Resource
    private UserService userService;

    /**
     * 根据用户ID从Redis和数据库查用户信息
     *
     * @param userId
     * @return
     */
    public User getUserByUserId(Object userId) {
        if (userId == null) {
            return null;
        }

        try {
            String value = redisUtil.getValueFromString(PREFIX_USER, userId);
            if (StringUtils.isNotBlank(value)) {
                return mapper.readValue(value, User.class);
            }

            User user = userService.findUserById(Integer.parseInt(userId.toString()));
            if (user != null) {
                userService.saveUserInfoToRedis(user);
            }
            return user;
        } catch (JsonProcessingException e) {
            log.error(e.toString());
        }
        return null;
    }

}
